import {
  Component,
  OnInit,
  ElementRef,
  DoCheck,
  OnDestroy,
  Inject,
  Input,
  EventEmitter,
  Directive
} from "@angular/core";
import {
  LocaleService,
  TranslationService,
  Language,
  DefaultLocale
} from "angular-l10n";

import { fromEvent, of, Subject, combineLatest } from "rxjs";
import { FormControl } from "@angular/forms";

import { Store, select } from "@ngrx/store";
import * as fromTrade from "@/trade/store/reducers/index";
import { map, filter, skip, switchMap } from "rxjs/operators";
import { Subscription } from "rxjs";
import { UserActions } from "@/user/store/actions";
import { combineAll, debounceTime } from "rxjs/operators";
import { TradeActions } from "@/trade/store/actions";
import * as fromRoot from "@/reducers/index";
import * as fromUser from "@/user/store/reducers/index";
import { ISelectActiveRequest } from "@/trade/store/models/trade";
import { ActivatedRoute } from "@angular/router";
import { PageEvent } from "@angular/material";

export interface IOrderItemAction {
  label: string;
  type: string;
  onClick: Function;
}

export interface IOrderItem {
  id: string;
  time: number;
  zi: string;
  mu: string;
  type: "buy" | "sell";
  price: string;
  amount: string;
  used: string;
  tab: "active" | "history";
  action: Array<IOrderItemAction>;
}

export interface IPage {
  total: number;
}

@Component({
  selector: "app-panel-active",
  templateUrl: "./panel-active.component.html",
  styleUrls: ["./panel-active.component.scss"]
})
export class PanelActiveComponent implements OnInit, DoCheck, OnDestroy {
  @Language() lang: string;

  tabs = [
    { name: "i18n.trade.active", type: "active" },
    { name: "i18n.trade.history", type: "history" }
  ];

  @Input() tab = "active";

  @DefaultLocale() defaultLocale: string;

  onTab = new FormControl();

  show = false;

  page: IPage = {
    total: 0
  };

  filters = [
    { name: "All", type: "all" },
    { name: "Buy", type: "buy" },
    { name: "Sell", type: "sell" }
  ];

  onFilter = new FormControl();

  user$ = this.store.pipe(
    select(fromRoot.user),
    filter(user => !!user)
  );

  addOrderSuccess$ = this.store.pipe(
    select(fromRoot.addOrderRes),
    filter(e => e.code === 200)
  );

  delOrderSuccess$ = this.store.pipe(
    select(fromRoot.delOrderRes),
    filter(e => e.code === 200)
  );

  lists$ = this.store.pipe(
    select(fromRoot.activeLists),
    filter(activeLists => !!activeLists)
  );

  listsRes$ = this.store.pipe(
    select(fromRoot.activeListsRes),
    filter(e => e.code !== -1)
  );

  isLogin$ = this.store.pipe(
    select(fromRoot.userRes),
    filter(e => e.code !== -1),
    map(e => e.code === 200)
  );

  isNoData = false;

  activeOrder = [];
  historyOrder = [];

  lists: Array<IOrderItem> = [];

  el: ElementRef;

  req: ISelectActiveRequest = {
    uid: "",
    zi: "",
    mu: "",
    p: 1,
    size: 10
  };

  sub$ = {
    activeListsSub$: null,

    filterSub$: null,

    listsSub$: null,

    listsResSub$: null,

    addOrderResSub$: null,
    delOrderResSub$: null
  };

  constructor(
    el: ElementRef,
    private store: Store<fromTrade.State | fromUser.State | fromRoot.State>,
    private activeRouter: ActivatedRoute,
    @Inject("DialogService") private dialogService,
    @Inject("UtilsService") private utilsService
  ) {
    this.el = el;
  }

  ngOnInit() {
    this.addListen();
  }

  addListen() {
    this.sub$.activeListsSub$ = combineLatest(
      this.user$,
      this.activeRouter.queryParams
    ).subscribe(([user, query]) => {
      this.req.uid = user.id;
      const [zi, mu] = query.symbol.split("_");
      this.req.zi = zi;
      this.req.mu = mu;

      this.store.dispatch(new TradeActions.SelectActive({ req: this.req }));
    });

    this.sub$.filterSub$ = combineLatest(
      this.onTab.valueChanges,
      this.onFilter.valueChanges,
      this.lists$
    ).subscribe(([onTab, onFilter, lists]) => {
      this.lists = lists
        .slice()
        .filter(d => {
          return d.tab === onTab.type;
        })
        .filter(d => {
          if (onFilter.type === "all") {
            return true;
          }
          return d.type === onFilter.type;
        })
        .map(d => {
          return {
            ...d,
            action: [
              {
                label: "撤单",
                onClick: (e, item) => {
                  e.stopPropagation();
                  this.dialogService
                    .confirm("confirm.revoke")
                    .afterClosed()
                    .subscribe(b => {
                      if (!b) {
                        return;
                      }
                      this.store.dispatch(
                        new TradeActions.DelOrder({
                          req: { id: item.id }
                        })
                      );
                    });
                },
                type: "del"
              }
            ]
          };
        });
    });

    this.onTab.setValue(this.tab === "active" ? this.tabs[0] : this.tabs[1]);
    this.onFilter.setValue(this.filters[0]);

    this.sub$.listsResSub$ = this.listsRes$.subscribe(e => {
      this.page.total = e.total;
    });

    this.sub$.addOrderResSub$ = this.addOrderSuccess$.subscribe(e => {
      this.store.dispatch(new TradeActions.SelectActive({ req: this.req }));
    });

    this.sub$.delOrderResSub$ = this.delOrderSuccess$.subscribe(e => {
      this.store.dispatch(new TradeActions.SelectActive({ req: this.req }));
    });
  }

  onChangePage(e) {
    const { pageIndex: p, pageSize: size } = e;

    this.req.p = p;
    this.req.size = size;

    this.store.dispatch(new TradeActions.SelectActive({ req: this.req }));
  }

  onChangeTab(item) {
    this.onTab.setValue(item);
  }

  setOnFilter(e, item) {
    e.stopPropagation();
    this.onFilter.setValue(item);
  }

  saveOrder(item) {}

  ngDoCheck() {}

  ngOnDestroy() {
    this.utilsService.unsub(this.sub$);
  }
}
